﻿using NB.MGJ.Cache;
using NB.MGJ.Common.Helper;
using NB.MGJ.Common.Utility;
using NB.MGJ.FrameWork;
using NB.MGJ.Model;
using NB.MGJ.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace NB.MGJ.Common.Cache
{
    public static class UserHelper
    {
  
        public static LogOnUserModel SetUserToSession(L.EntityModel.V_User _user)
        {

            
            string temp = "";
            if (_user.UserImg == null || _user.UserImg == "")
            {
                temp = "/Images/UserAvatar/05313d981a475860d9d14f63654785c0.png";
            }
            else
            {
                temp = _user.UserImg;
            }
            var _logonUser = new LogOnUserModel
            {
                UserID = _user.ID,
                EnterpriseId = _user.EnterpriseId,
                LoginName = _user.LoginName,
                RealName = _user.RealName,
                Modile = _user.Modile,
                //    Province = Convert.ToInt32(_user.Province),
                //     City= Convert.ToInt32(_user.City),
                EnterpriseName = _user.EnterpriseName,
                UserImg = temp,
                OrganizationLogo = _user.Img,
                Distributor=_user.Distributor,
                JuniorEnterprise=" getJuniorEnterprise("+_user.EnterpriseId+")",
                RoleID = GetRoles(_user.ID) ,
                ECode=_user.Code ,
                HeadId=_user.HeadId,
                FromTypeRole =GetFromTypeRole(_user.ID),
                AdminRoleID=_user.AdminRoleID
            };
            
            SessionHelper.LogOnUser<LogOnUserModel>(_logonUser);
            //SessionHelper.Set<LogOnUserModel>(_logonUser.UserID.ToString(), _logonUser);
            bool RoleType =false;  // 用户角色是否和 门面 子门面 仓库 农场 经销商(品控管理员)有关联 
              int [] arr={8,9,22,10,12}; 
          
             
            foreach (var item in _logonUser.FromTypeRole.Split(','))
	        {
                if (RoleType)
	            {
		                break;
                }
		             foreach (int ar in arr)
	                 {
		                          if (ar==int.Parse(item))
	                             {
		                          RoleType=true;
                                     break;
                                  }
                     }   
            }
            
            string sql = "";
           
            
            if (_user.ID == 1)    //判断andmin
            {

                sql = "select ID As MenuID,ID,ParentId,MenuName,MenuImg,ActionName,Controller,StatusID,Remark,Sequence,MenuType,isParent from Sys_Menu  ORDER BY Sequence";
            }
            else if (_user.Distributor!=0 )     //经销商
            {
                sql = string.Format(@"SELECT * FROM 
                 (
                 select DISTINCT MenuID from Sys_MenuRoleInfo where Rid in (select Rid from Sys_RoleUserInfo ru LEFT JOIN sys_role r on ru.Rid=r.ID where ru.uId='{0}')
                 ) a
                 LEFT JOIN Sys_Menu b ON a.MenuID = b.ID where menuID not in({1})  ORDER BY Sequence", _user.ID,  "76,77,8,23,15,82"); //如果
            }
            else if (RoleType)   // 门面 子门面 仓库 农场(品控管理员)  没有添加下级机构的权限   排除机构管理
           	{
                sql = string.Format(@"SELECT * FROM 
                 (
                 select DISTINCT MenuID from Sys_MenuRoleInfo where Rid in (select Rid from Sys_RoleUserInfo ru LEFT JOIN sys_role r on ru.Rid=r.ID where ru.uId='{0}' )
                 ) a
                 LEFT JOIN Sys_Menu b ON a.MenuID = b.ID where menuID not in({1})  ORDER BY Sequence", _user.ID, _user.HeadId == 1 ? "0,8,23,15" : "76,77,8,23,15,82"); //如果 HeadId 0诺标   1 总部    大于1是子公司

           	}
            else      //企业用户
            {
                 //修改人：huajun 修改时间：2017/12/09
                 //                sql = @" SELECT
                 //                             * FROM
                 //                             (SELECT DISTINCT MenuID,IsAdd,IsDel,IsUpd
                 //                              FROM Sys_MenuRoleInfo	WHERE	Rid IN 
                 //                             (SELECT d.ButtonId 
                 //                                FROM Sys_User AS a	
                 //                                LEFT OUTER JOIN Organization_Enterprise AS b ON a.EnterpriseId = b.ButtonId
                 //				                INNER JOIN  Sys_RoleUserInfo  c ON a.ButtonId = c.Uid
                 //				                INNER JOIN  Sys_Role d ON d.ButtonId = c.Rid
                 //				                WHERE (a.ViewDel = 0) AND (a.ViewFlag = 1)
                 //				                AND a.ButtonId = '" + _user.ButtonId + "'))  mr LEFT JOIN Sys_Menu m ON mr.MenuID = m.ButtonId";

                //如果 HeadId是1 代表是总部  否则是子机构
                                 sql =string.Format(@"SELECT * FROM 
                 (
                 select DISTINCT MenuID from Sys_MenuRoleInfo where Rid in (select Rid from Sys_RoleUserInfo ru LEFT JOIN sys_role r on ru.Rid=r.ID where ru.uId='{0}' )
                 ) a
                 LEFT JOIN Sys_Menu b ON a.MenuID = b.ID where menuID not in({1})  ORDER BY Sequence", _user.ID, _user.HeadId == 1 ? "0,15,23" : "76,77,15,82,23"); 

            }

            //UserHelper.UpdateMenuCache(sql);//正式上线删除掉先更新菜单缓存
            //CompleteUserMenuList(_logonUser,sql);
            CompleteUserMenuList_New(_logonUser, sql);
            return _logonUser;
        }

        /// <summary>
        /// 获取当前用户角色 不包括服务版本
        /// </summary>
        /// <param name="Uid"></param>
        /// <returns></returns>
        public static string GetFromTypeRole(int Uid)
        {
            string sql = "select GROUP_CONCAT(rid)  as Rids  from sys_roleuserinfo ru left join sys_role r on ru.Rid=r.ID  where Uid=" + Uid + " and r.isVersions=0 ";
            BaseRepository _b = new BaseRepository();
            var result = _b.GetSingle(sql);
            return Object.Equals(result, null) ? Uid.ToString() : result.ToString().TrimEnd(',');
        }
        /// <summary>
        /// 获取当前用户角色 包括服务版本
        /// </summary>
        /// <param name="Uid"></param>
        /// <returns></returns>
        public static string GetRoles(int Uid) 
        {
            string sql = "select GROUP_CONCAT(rid)  as Rids  from sys_roleuserinfo where Uid="+Uid;
            BaseRepository _b = new BaseRepository();
                var result= _b.GetSingle(sql);
            return Object.Equals(result, null) ?Uid.ToString():result.ToString().TrimEnd(',');
        }

        public static void CompleteUserMenuList_New(LogOnUserModel model, string sql)
        {
            var _list = CacheManager.Get<List<Sys_Menu>>(CacheKey.Key_AllMenuInfoList, () =>
            {
                return new CommonService().GetAllMenuInfoList(sql);
            }, true);
            //给三个新东西复制
            model.menus = new List<UserMenuItem>();
            model.actionControllers = new List<string>();
            UserMenuItem _menudata = null;

            foreach (var item in _list)
            {

                if (item.ActionName != null && item.Controller != null)
                    model.actionControllers.Add(item.Controller + "_" + item.ActionName);

                if (item.ParentId == 0)
                {
                    _menudata = new UserMenuItem
                    {
                        menuno = item.ID,
                        menuname = item.MenuName,
                        actionname = item.ActionName,
                        controller = item.Controller,
                        isgroup = (item.ActionName == null || item.Controller == null) ? true : false,
                        icon = item.MenuImg,
                        isadd = item.IsAdd,
                        isdel = item.IsDel,
                        isupd = item.IsUpd
                    };
                    _menudata.menus = new List<UserMenuItem>();
                    foreach (var item2 in _list)
                    {
                        if (item2.ParentId == item.ID)
                        {
                            _menudata.menus.Add(new UserMenuItem()
                            {
                                menuno = item2.ID,
                                menuname = item2.MenuName,
                                actionname = item2.ActionName,
                                controller = item2.Controller,
                                isgroup = false,
                                icon = item2.MenuImg,
                                isadd = item2.IsAdd,
                                isdel = item2.IsDel,
                                isupd = item2.IsUpd
                            });
                        }
                    }
                    model.menus.Add(_menudata);
                }
            }

        }



      
        /// <summary>
        /// 主动更新菜单缓存信息
        /// </summary>
        public static void UpdateMenuCache(string sql)
        {
            MGJCache.UpdateMenuCache(sql);
        }


        public static List<UserMenuItem> GetUserMenuList(this HtmlHelper helper)
        {
            return SessionHelper.LogOnUser<LogOnUserModel>().menus;
        }


    }
}
